<template>
  <div class="plan-task">
    <!-- 计划任务表格 -->
    <el-table
      v-loading="listLoading"
      :data="disposeFormListViewTime(tableData, columns)"
      header-row-class-name="common-list-table-header__v2"
      :class="['bbx-normal-list-box']"
      stripe
      border
      max-height="500"
    >
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>
      <el-table-column
        v-for="column in columns"
        :key="column.id"
        :prop="column.field"
        :label="column.displayName"
        :fixed="column.isFixed"
        :width="column.width"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <template v-if="column.field === 'planNumber'">
            <span class="link" @click="jumpPlanTaskTab(row.id)">{{
              row.planNumber || ''
            }}</span>
          </template>
          <template v-else-if="column.field === 'name'">
            <span class="link" @click="jumpPlanTaskTab(row.id)">{{
              row.name || ''
            }}</span>
          </template>
          <template v-else-if="column.field === 'customer'">
            <span class="link" @click="jumpCustomerTab(row.task.customer.id)">{{
              row.task.customer.name || ''
            }}</span>
          </template>
          <template v-else-if="column.field === 'products'">
            <span
              class="link"
              v-for="(item, index) in row.task.products"
              :key="item.id"
              @click="jumpProductTab(item.id)"
              >{{
                (index == row.task.products.length - 1 && item.name) ||
                item.name + '，'
              }}</span
            >
          </template>
          <template v-else-if="column.field === 'serialNumber'">
            <span>{{ productSerialNumberFormat(row.task.products) }}</span>
          </template>
          <template v-else-if="column.field === 'createdTasks'">
            <span
              class="link"
              v-for="(item, index) in row.createdTasks"
              :key="item.taskId"
              @click="jumpTaskTab(item.taskId)"
              >{{
                (index == row.createdTasks.length - 1 && item.taskNo) ||
                item.taskNo + '，'
              }}</span
            >
          </template>


          <template v-else-if="column.field == 'nextTaskCreateTime' || column.field == 'createTime'">
            {{ row[column.field] | fmt_datetime}}
          </template>

          <template v-else-if="column.field === 'templateName'">
            {{row.task.templateName}}
          </template>
          <template v-else-if="column.field === 'periodSetting'">
            <!-- TODO 国际化 bell -->
            {{ $t('common.base.per') }}{{row[column.field].period + row[column.field].periodUnit}}
          </template>
          <template v-else-if="column.field === 'executorUserName'">
            {{row.allotSetting.executorName}}
          </template>
          <template v-else-if="column.field === 'endSetting'">
            <template v-if="row.endSetting.endBy === 'date'">
              {{row.endSetting.value | fmt_datetime}}
            </template>
            <template v-else>
              {{ $t('product.detail.planTable.text1' , {count : row.endSetting.value}) }}
            </template>
          </template>
          <template v-else-if="column.field == 'operation'">
            <span class="edit-btn pub-btn" @click="jumpPlanTaskTab(row.id, 'operation')"
              >{{$t('common.base.edit')}}</span
            >
            <span
              class="mar-l-10 del-btn pub-btn"
              @click="handleClickDel(row.id)"
              >{{$t('common.base.delete')}}</span
            >
          </template>
          
          <template v-else>
            {{ row[column.field] }}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="tableData.length" class="table-footer">

      <i18n path="common.base.table.totalCount">
        <span place="count" class="level-padding">{{ page.total }}</span>
      </i18n>
      
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page.sync="page.pageNum"
        :page-size="page.pageSize"
        layout="prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import {
  onMounted,
  reactive,
  toRefs,
  computed,
  ref,
} from 'vue';
import i18n from '@src/locales';

import platform from '@src/platform';

import { MessageBox } from 'element-ui';

import { deletePlanTask } from '@src/api/TaskApi.ts';
import { planTaskListView } from '@src/api/ContractApi';
import { useFormTimezone, formatDate } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()

import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'

import { getRootWindow } from '@src/util/dom';

import { productSerialNumberFormat } from '@src/modules/contract/util/productFormat.js'

export default {
  setup() {
    const columns = ref([
      // {
      //   id: 1,
      //   displayName: i18n.t('common.fields.orderNo.displayName'),
      //   field: 'orderNumber',
      // },
      {
        id: 2,
        displayName: i18n.t('common.fields.planNumber.displayName'),
        field: 'planNumber',
      },
      {
        id: 3,
        displayName: i18n.t('common.fields.taskName.displayName'),
        field: 'name',
      },
      {
        id: 4,
        displayName: i18n.t('common.fields.taskType.displayName'),
        field: 'templateName',
      },
      {
        id: 5,
        displayName: i18n.t('common.fields.customer.displayName'),
        field: 'customer',
      },
      {
        id: 6,
        displayName: i18n.t('common.fields.product.displayName'),
        field: 'products',
      },
      {
        id: 7,
        displayName: i18n.t('common.fields.productNo.displayName'),
        field: 'serialNumber',
      },
      {
        id: 8,
        displayName: i18n.t('common.fields.repetitionPeriod.displayName'),
        field: 'periodSetting',
      },
      {
        id: 9,
        displayName: i18n.t('common.fields.nextCreateTime.displayName'),
        field: 'nextTaskCreateTime',
      },
      {
        id: 10,
        displayName: i18n.t('common.fields.deadline.displayName'),
        field: 'endSetting',
      },
      {
        id: 11,
        displayName: i18n.t('common.fields.executorUser.displayName'),
        field: 'executorUserName',
      },
      {
        id: 12,
        displayName: i18n.t('common.fields.createUser.displayName'),
        field: 'createUserName',
      },
      {
        id: 13,
        displayName: i18n.t('common.fields.createTime.displayName'),
        field: 'createTime',
      },
      {
        id: 15,
        displayName: i18n.t('product.detail.type.plan.totalTaskNumber'), // 总工单数
        field: 'totalTaskNumber',
        width: 100
      },
      {
        id: 16,
        displayName: i18n.t('product.detail.type.plan.uncreateTaskNumber'), // 待创建工单数
        field: 'uncreatedTaskNumber',
        width: 100
      },
      {
        id: 17,
        displayName: i18n.t('product.detail.type.plan.createTaskNumber'), // 已创建工单数
        field: 'createdTasks',
        width: 100
      },
      {
        id: 18,
        displayName: i18n.t('product.detail.type.plan.finishedTaskNumber'), // 已完成工单数
        field: 'finishedTaskNumber',
        width: 100
      },
      {
        id: 14,
        displayName: i18n.t('common.fields.action.displayName'),
        field: 'operation',
        isFixed: 'right',
        width: '100',
        align: 'center',
      },
    ]);

    const state = reactive({
      tableData: [],
      listLoading: false,
      page: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
    });

    // 合同id
    const contractId = computed(() => {
      return location.pathname.split('/contract/view/')[1] || '';
    });

    // 华大基因灰度
    const isBgiSaas = computed(() => {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.bgiSaas)
    })

    // 获取计划任务列表
    const getPlanList = async () => {
      state.listLoading = true;
      state.tableData = [];

      try {
        let res = await planTaskListView({
          contractId: contractId.value,
          ...state.page,
        });

        if (!res.success)
          return platform.notification({
            title: res.message,
            type: 'error',
          });

        let { list, total } = res.result;

        list.forEach(plan => {
          plan.createTime = formatDate(plan.createTime, 'YYYY-MM-DD HH:mm:ss');
          plan.nextTaskCreateTime = plan.nextTaskCreateTime ? formatDate(plan.nextTaskCreateTime, 'YYYY-MM-DD HH:mm:ss') : '';
        });
        state.tableData = list || [];
        state.page.total = total;
      } catch (error) {
        console.log('error=>', error);
      } finally {
        state.listLoading = false;
      }
    };

    // 页数改变时触发
    const handleCurrentChange = pageNum => {
      state.page.pageNum = pageNum;
      getPlanList();
    };

    /** 跳转编辑计划任务 */
    const jumpPlanTaskTab = (planTaskId, type) => {
      if (!planTaskId) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: isBgiSaas.value && type != 'operation' ? PageRoutesTypeEnum.PagePlanTaskView : PageRoutesTypeEnum.PagePlanTaskEdit,
        key: planTaskId,
        params: `id=${planTaskId}`,
        reload: true,
        fromId
      })
    };

    /** 跳转客户详情 */
    const jumpCustomerTab = customerId => {
      if (!customerId) return;

      let fromId = window.frameElement?.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
    };

    /** 跳转产品详情 */
    const jumpProductTab = productId => {
      if (!productId) return;

      let fromId = window.frameElement?.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    };

    /** 跳转工单 */
    const jumpTaskTab = taskId => {
      if (!taskId) return;
  
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        params:'noHistory=1',
        fromId
      })
    };

    // 点击删除
    const handleClickDel = id => {
      MessageBox.confirm(i18n.t('contract.planTaskTable.delConfirmMsg'), i18n.t('common.base.toast'), {
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            deletePlanTask({ ids: [id] }).then(res => {
              instance.confirmButtonLoading = false;
              if (!res.success) {
                return platform.notification({
                  title: res.message,
                  type: 'error',
                });
              }
              platform.notification({
                title: i18n.t('common.base.deleteSuccess'),
                type: 'success',
              });

              handleCurrentChange(1);
              done();
            });
          } else {
            done();
          }
        },
      });
    };

    onMounted(() => {
      getPlanList();
    });
    return {
      columns,
      ...toRefs(state),
      handleCurrentChange,
      jumpPlanTaskTab,
      jumpCustomerTab,
      jumpProductTab,
      jumpTaskTab,
      handleClickDel,
      disposeFormListViewTime,
      productSerialNumberFormat,
    };
  },
};
</script>
<style lang="scss" scoped>
@import './Statistics.scss';

.plan-task {
  height: calc(100% - 108px);
  overflow-y: auto;
  padding: 0 16px;
}
</style>